<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TECH CHAT 3000 - 多用户聊天</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link
      href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css"
      rel="stylesheet"
    />
    <script>
      tailwind.config = {
        theme: {
          extend: {
            colors: {
              primary: "#165DFF",
              secondary: "#0F172A",
              dark: "#0A0F1C",
              light: "#E2E8F0",
              accent: "#3B82F6",
            },
            fontFamily: {
              sans: ["Inter", "system-ui", "sans-serif"],
            },
          },
        },
      };
    </script>
    <style type="text/tailwindcss">
      @layer utilities {
        .content-auto {
          content-visibility: auto;
        }
        .scrollbar-thin {
          scrollbar-width: thin;
        }
        .scrollbar-thin::-webkit-scrollbar {
          width: 4px;
        }
        .scrollbar-thin::-webkit-scrollbar-thumb {
          background-color: rgba(156, 163, 175, 0.5);
          border-radius: 2px;
        }
      }
    </style>
  </head>
  <body class="bg-dark text-light font-sans min-h-screen flex flex-col">
    <!-- 顶部导航 -->
    <header
      class="bg-secondary border-b border-gray-700 px-4 py-3 flex items-center justify-between"
    >
      <div class="flex items-center space-x-2">
        <i class="fa fa-comments text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">TECH CHAT 3000</h1>
      </div>
      <div class="flex items-center space-x-4">
        <div id="connection-status" class="flex items-center">
          <span
            id="status-indicator"
            class="w-2 h-2 rounded-full bg-red-500 mr-2"
          ></span>
          <span id="status-text">未连接</span>
        </div>
        <button
          id="user-login"
          class="bg-primary hover:bg-primary/80 text-white px-4 py-2 rounded-md transition"
        >
          <i class="fa fa-user mr-1"></i> 登录
        </button>
      </div>
    </header>

    <div class="flex flex-1 overflow-hidden">
      <!-- 左侧边栏 -->
      <aside class="w-64 bg-secondary border-r border-gray-700 flex flex-col">
        <!-- 房间列表 -->
        <div class="p-4 border-b border-gray-700">
          <h2 class="font-semibold mb-2">聊天房间</h2>
          <div class="space-y-1">
            <button
              class="room-btn w-full text-left px-3 py-2 rounded hover:bg-gray-700/50 transition"
              data-room="general"
            >
              <i class="fa fa-globe mr-2"></i> 公共大厅
            </button>
            <button
              class="room-btn w-full text-left px-3 py-2 rounded hover:bg-gray-700/50 transition"
              data-room="tech"
            >
              <i class="fa fa-code mr-2"></i> 技术讨论
            </button>
            <button
              class="room-btn w-full text-left px-3 py-2 rounded hover:bg-gray-700/50 transition"
              data-room="random"
            >
              <i class="fa fa-random mr-2"></i> 闲聊
            </button>
          </div>
        </div>

        <!-- 当前房间用户 -->
        <div class="flex-1 overflow-y-auto scrollbar-thin p-4">
          <h2 class="font-semibold mb-2">
            当前在线 (<span id="user-count">0</span>)
          </h2>
          <div id="user-list" class="space-y-2">
            <!-- 用户列表将动态填充 -->
          </div>
        </div>

        <!-- 服务器信息 -->
        <div class="p-4 border-t border-gray-700 text-sm text-gray-400">
          <div class="mb-2">
            <h3 class="font-medium text-gray-300 mb-1">服务器信息</h3>
            <p>IP: localhost</p>
            <p>端口: 8080</p>
            <p>协议: WebSocket</p>
          </div>
          <div>
            <h3 class="font-medium text-gray-300 mb-1">连接状态</h3>
            <p id="connection-time">未连接</p>
          </div>
        </div>
      </aside>

      <!-- 主聊天区域 -->
      <main class="flex-1 flex flex-col overflow-hidden">
        <!-- 聊天消息区域 -->
        <div
          id="chat-messages"
          class="flex-1 overflow-y-auto scrollbar-thin p-6 space-y-6 bg-[#0F172A]/50"
        >
          <!-- 系统欢迎消息 -->
          <div class="system-message max-w-3xl mx-auto">
            <div class="bg-gray-800/50 p-4 rounded-lg">
              <div class="flex items-start">
                <i class="fa fa-info-circle text-primary mt-1 mr-3"></i>
                <div>
                  <p class="text-gray-300">
                    欢迎使用 TECH CHAT 3000 多用户聊天系统
                  </p>
                  <p class="text-gray-400 text-sm mt-1">
                    请先登录并选择一个房间开始聊天
                  </p>
                  <p class="text-gray-500 text-xs mt-1">
                    系统时间: <span id="system-time"></span>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 消息输入区域 -->
        <div class="border-t border-gray-700 p-4 bg-secondary">
          <div class="flex items-end space-x-3">
            <div class="flex-1">
              <textarea
                id="message-input"
                placeholder="输入消息... (按Enter发送，Shift+Enter换行)"
                class="w-full bg-dark border border-gray-700 rounded-md p-3 focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none transition"
                rows="3"
              ></textarea>
            </div>
            <div>
              <button
                id="send-button"
                class="bg-primary hover:bg-primary/80 text-white px-6 py-3 rounded-md transition disabled:opacity-50 disabled:cursor-not-allowed"
                disabled
              >
                <i class="fa fa-paper-plane mr-1"></i> 发送
              </button>
            </div>
          </div>
          <p class="text-gray-500 text-xs mt-2">
            当前房间: <span id="current-room">未选择</span>
          </p>
        </div>
      </main>
    </div>

    <!-- 登录模态框 -->
    <div
      id="login-modal"
      class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden"
    >
      <div
        class="bg-secondary rounded-lg shadow-xl w-full max-w-md p-6 border border-gray-700"
      >
        <h2 class="text-xl font-bold mb-4">用户登录</h2>
        <div class="mb-4">
          <label for="username" class="block text-sm font-medium mb-1"
            >用户名</label
          >
          <input
            type="text"
            id="username"
            class="w-full bg-dark border border-gray-700 rounded-md p-2 focus:outline-none focus:ring-2 focus:ring-primary/50"
            placeholder="请输入用户名"
          />
        </div>
        <div class="flex justify-end space-x-2">
          <button
            id="cancel-login"
            class="px-4 py-2 border border-gray-700 rounded-md hover:bg-gray-700/30 transition"
          >
            取消
          </button>
          <button
            id="confirm-login"
            class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/80 transition"
          >
            登录
          </button>
        </div>
      </div>
    </div>

    <script>
      // 全局变量
      let websocket;
      let username = null;
      let currentRoom = null;
      let connected = false;

      // DOM 元素
      const chatMessages = document.getElementById("chat-messages");
      const messageInput = document.getElementById("message-input");
      const sendButton = document.getElementById("send-button");
      const statusIndicator = document.getElementById("status-indicator");
      const statusText = document.getElementById("status-text");
      const connectionTime = document.getElementById("connection-time");
      const userList = document.getElementById("user-list");
      const userCount = document.getElementById("user-count");
      const currentRoomEl = document.getElementById("current-room");
      const systemTimeEl = document.getElementById("system-time");
      const userLoginBtn = document.getElementById("user-login");
      const loginModal = document.getElementById("login-modal");
      const usernameInput = document.getElementById("username");
      const confirmLoginBtn = document.getElementById("confirm-login");
      const cancelLoginBtn = document.getElementById("cancel-login");
      const roomButtons = document.querySelectorAll(".room-btn");

      // 更新发送按钮状态
      function updateSendButtonState() {
        const hasContent = messageInput.value.trim().length > 0;
        const canSend = connected && username && currentRoom && hasContent;
        sendButton.disabled = !canSend;
      }

      // 更新系统时间
      function updateSystemTime() {
        const now = new Date();
        systemTimeEl.textContent = now.toLocaleString();
      }
      setInterval(updateSystemTime, 1000);
      updateSystemTime();

      // 连接 WebSocket 服务器
      function connectWebSocket() {
        if (websocket && websocket.readyState === WebSocket.OPEN) {
          return;
        }

        // 连接到 WebSocket 服务器
        const wsUri = "ws://localhost:8080";
        websocket = new WebSocket(wsUri);

        // 连接打开时
        websocket.onopen = function () {
          connected = true;
          statusIndicator.className = "w-2 h-2 rounded-full bg-green-500 mr-2";
          statusText.textContent = "已连接";
          connectionTime.textContent = new Date().toLocaleString();

          // 如果已登录，发送登录信息
          if (username) {
            sendMessage({
              type: "login",
              username: username,
            });
          }

          // 更新发送按钮状态
          updateSendButtonState();
        };

        // 收到消息时
        websocket.onmessage = function (event) {
          const message = JSON.parse(event.data);
          handleMessage(message);
        };

        // 连接关闭时
        websocket.onclose = function () {
          connected = false;
          statusIndicator.className = "w-2 h-2 rounded-full bg-red-500 mr-2";
          statusText.textContent = "已断开";
          addSystemMessage("与服务器的连接已断开，正在尝试重连...");

          // 更新发送按钮状态
          updateSendButtonState();

          // 尝试重连
          setTimeout(connectWebSocket, 3000);
        };

        // 发生错误时
        websocket.onerror = function (error) {
          console.error("WebSocket 错误:", error);
          addSystemMessage("连接发生错误");
        };
      }

      // 发送消息
      function sendMessage(data) {
        if (websocket && websocket.readyState === WebSocket.OPEN) {
          websocket.send(JSON.stringify(data));
        }
      }

      // 处理收到的消息
      function handleMessage(message) {
        switch (message.type) {
          case "system":
            addSystemMessage(message.content);
            break;
          case "chat":
            addChatMessage(
              message.username,
              message.content,
              message.timestamp
            );
            break;
          case "userList":
            updateUserList(message.users);
            break;
          case "roomChange":
            currentRoom = message.room;
            currentRoomEl.textContent = formatRoomName(currentRoom);
            addSystemMessage(`已进入房间: ${formatRoomName(currentRoom)}`);
            // 更新发送按钮状态
            updateSendButtonState();
            break;
          default:
            console.log("收到未知类型消息:", message);
        }
      }

      // 添加系统消息
      function addSystemMessage(content) {
        const now = new Date();
        const timeString = now.toLocaleTimeString();

        const messageEl = document.createElement("div");
        messageEl.className = "system-message max-w-3xl mx-auto";
        messageEl.innerHTML = `
                <div class="bg-gray-800/50 p-4 rounded-lg">
                    <div class="flex items-start">
                        <i class="fa fa-info-circle text-primary mt-1 mr-3"></i>
                        <div>
                            <p class="text-gray-300">${content}</p>
                            <p class="text-gray-500 text-xs mt-1">${timeString}</p>
                        </div>
                    </div>
                </div>
            `;

        chatMessages.appendChild(messageEl);
        scrollToBottom();
      }

      // 添加聊天消息
      function addChatMessage(username, content, timestamp) {
        const isOwnMessage = username === this.username;
        const timeString = timestamp
          ? new Date(timestamp).toLocaleTimeString()
          : new Date().toLocaleTimeString();

        const messageEl = document.createElement("div");
        messageEl.className = `message max-w-3xl mx-auto ${
          isOwnMessage ? "flex justify-end" : "flex"
        }`;

        const messageContent = `
                <div class="${
                  isOwnMessage
                    ? "bg-primary text-white"
                    : "bg-gray-800/50 text-gray-200"
                } p-4 rounded-lg max-w-[80%]">
                    <div class="flex items-center mb-1">
                        <span class="font-medium ${
                          isOwnMessage ? "" : "text-primary"
                        }">${username}</span>
                        <span class="text-gray-400 text-xs ml-2">${timeString}</span>
                    </div>
                    <p>${content}</p>
                </div>
            `;

        messageEl.innerHTML = messageContent;
        chatMessages.appendChild(messageEl);
        scrollToBottom();
      }

      // 更新用户列表
      function updateUserList(users) {
        userList.innerHTML = "";
        userCount.textContent = users.length;

        users.forEach((user) => {
          const userEl = document.createElement("div");
          userEl.className = `flex items-center px-2 py-1 rounded ${
            user === username ? "bg-primary/20" : "hover:bg-gray-700/30"
          }`;
          userEl.innerHTML = `
                    <span class="w-2 h-2 rounded-full bg-green-500 mr-2"></span>
                    <span>${user}</span>
                    ${
                      user === username
                        ? '<span class="ml-auto text-xs bg-primary/30 px-1.5 py-0.5 rounded">你</span>'
                        : ""
                    }
                `;
          userList.appendChild(userEl);
        });
      }

      // 切换房间
      function joinRoom(room) {
        if (!username) {
          showLoginModal();
          return;
        }

        currentRoom = room;
        sendMessage({
          type: "joinRoom",
          room: room,
          username: username,
        });
      }

      // 格式化房间名称
      function formatRoomName(room) {
        const roomNames = {
          general: "公共大厅",
          tech: "技术讨论",
          random: "闲聊",
        };
        return roomNames[room] || room;
      }

      // 滚动到底部
      function scrollToBottom() {
        chatMessages.scrollTop = chatMessages.scrollHeight;
      }

      // 显示登录模态框
      function showLoginModal() {
        loginModal.classList.remove("hidden");
        usernameInput.focus();
      }

      // 隐藏登录模态框
      function hideLoginModal() {
        loginModal.classList.add("hidden");
      }

      // 发送聊天消息
      function sendChatMessage() {
        const content = messageInput.value.trim();
        if (!content || !username || !currentRoom || !connected) {
          return;
        }

        sendMessage({
          type: "chat",
          username: username,
          room: currentRoom,
          content: content,
          timestamp: new Date().toISOString(),
        });

        messageInput.value = "";
        // 更新发送按钮状态
        updateSendButtonState();
      }

      // 事件监听器
      sendButton.addEventListener("click", sendChatMessage);

      messageInput.addEventListener("input", updateSendButtonState);

      messageInput.addEventListener("keydown", function (event) {
        // 按 Enter 发送消息，Shift+Enter 换行
        if (event.key === "Enter" && !event.shiftKey) {
          event.preventDefault();
          sendChatMessage();
        }
      });

      userLoginBtn.addEventListener("click", function () {
        if (!username) {
          showLoginModal();
        } else {
          // 已登录状态下点击登录按钮可以切换用户
          username = null;
          this.innerHTML = '<i class="fa fa-user mr-1"></i> 登录';
          sendMessage({
            type: "logout",
            username: username,
          });
          addSystemMessage("已退出登录");
          // 更新发送按钮状态
          updateSendButtonState();
        }
      });

      confirmLoginBtn.addEventListener("click", function () {
        const inputUsername = usernameInput.value.trim();
        if (inputUsername) {
          username = inputUsername;
          userLoginBtn.innerHTML = `<i class="fa fa-user mr-1"></i> ${username}`;
          hideLoginModal();
          usernameInput.value = "";

          // 如果已连接，发送登录信息
          if (connected) {
            sendMessage({
              type: "login",
              username: username,
            });
          } else {
            // 否则先连接
            connectWebSocket();
          }

          addSystemMessage(`欢迎，${username}！请选择一个房间开始聊天`);
          // 更新发送按钮状态
          updateSendButtonState();
        }
      });

      cancelLoginBtn.addEventListener("click", hideLoginModal);

      roomButtons.forEach((button) => {
        button.addEventListener("click", function () {
          const room = this.getAttribute("data-room");
          joinRoom(room);

          // 更新按钮样式
          roomButtons.forEach((btn) => btn.classList.remove("bg-primary/20"));
          this.classList.add("bg-primary/20");
        });
      });

      // 初始化连接
      connectWebSocket();
    </script>
  </body>
</html>
